/*
 * @Description:
 * @Version: 2.0
 * @Autor: 胡彩丽 hucaili@qfei.cn
 * @LastEditors: 胡彩丽 hucaili@qfei.cn
 */
// 根据路由生成菜单
import { computed } from 'vue';
import { appRoutes } from '../routes';
import usePermission from '@/hooks/permission';
const totalMenus = appRoutes.map((el) => {
  const { name, path, meta, redirect, single, children } = el;
  return {
    name,
    path,
    meta,
    redirect,
    single,
    children
  };
});
// const { userInfo } = useUserStore();
export default function useMenuTree(path) {
  const permission = usePermission();
  const copyRouter = JSON.parse(JSON.stringify(totalMenus));
  copyRouter.sort((a, b) => {
    return (a.meta.order || 0) - (b.meta.order || 0);
  });
  let r = copyRouter;
  if (path) {
    r = copyRouter.find((el) => el.path === path)?.children;
  }
  const menuTree = computed(() => {
    const createUserMenus = (_routes) => {
      if (!_routes || !_routes.length) return null;
      const userMenuList = _routes.map((el) => {
        if (!permission.accessRouter(el) || el.meta?.hideInMenu) return null;
        if (el.meta?.single) return null;
        if (el.meta?.hideChildrenInMenu || !el.children) {
          el.children = [];
          return el;
        }
        // 下一级
        el.children = el.children.filter((ele) => ele.meta?.hideInMenu !== true);
        const subChildren = createUserMenus(el.children);
        if (subChildren.length) {
          el.children = subChildren;
          return el;
        }
        if (el.meta?.hideInMenu === false) {
          return el;
        }
        return null;
      });
      return userMenuList.filter(Boolean);
    };
    return createUserMenus(r);
  });
  return {
    menuTree
  };
}
